/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.fragment;

import java.util.Calendar;
import java.util.List;

import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.RunStopsIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.StopTimesIntentHolder;
import lt.marsrutai.mobile.android.model.ArrivalTime;
import lt.marsrutai.mobile.android.model.enums.DateTime;
import lt.marsrutai.mobile.android.model.enums.TrackType;
import lt.marsrutai.mobile.android.util.HourMinuteFormat;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.google.analytics.tracking.android.EasyTracker;

public class StopTimesFragment extends SherlockFragment {
    
    private List<ArrivalTime> arrivalTimes;
    private String trackId;

    public StopTimesFragment() {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.stop_times_view, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        receiveItemData(savedInstanceState);
        
        initialize();
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {        
        StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(outState);
        intentHolder.setArrivalTimes(arrivalTimes);
        intentHolder.setTrackId(trackId);        
        outState.putAll(intentHolder.getIntent().getExtras());        
        super.onSaveInstanceState(outState);
    }

    private void receiveItemData(Bundle bundle) {
        StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(bundle != null ? bundle : getArguments());
        arrivalTimes = intentHolder.getArrivalTimes();      
        trackId = intentHolder.getTrackId();
    }
    
    public void sendItemData(String runId, String scheduledTime) {        
        RunStopsIntentHolder intentHolder = new RunStopsIntentHolder(getActivity());
        
        StopTimesIntentHolder sourceIntentHolder = new StopTimesIntentHolder(getArguments());
        intentHolder.setScopeFolder(sourceIntentHolder.getScopeFolder());
        intentHolder.setScopeName(sourceIntentHolder.getScopeName());
        intentHolder.setTransportId(sourceIntentHolder.getTransportId());
        intentHolder.setScheduleId(sourceIntentHolder.getScheduleId());
        intentHolder.setScheduleName(sourceIntentHolder.getScheduleName());
        intentHolder.setScheduleTrackName(sourceIntentHolder.getScheduleTrackName());
        intentHolder.setTrackId(sourceIntentHolder.getTrackId());
        intentHolder.setTrackName(sourceIntentHolder.getTrackName());
        intentHolder.setStopId(sourceIntentHolder.getStopId());
        intentHolder.setStopName(sourceIntentHolder.getStopName());
        intentHolder.setStopDirectionName(sourceIntentHolder.getStopDirectionName());
                
        intentHolder.setRunId(runId);
        intentHolder.setScheduledTime(scheduledTime);
        
        startActivity(intentHolder.getIntent());
    }

    private void initialize() {
        setupArrivalTimes(getView());
    }

    private void setupArrivalTimes(View view) {
        TableLayout stopTimesTable = (TableLayout) view.findViewById(R.id.arrival_times);

        TableRow row = null;

        int currentHour = new DateTime().getCurrentHour();
        int currentMinute = new DateTime().getCurrentMinute();
        boolean foundNextTime = false; 
        
        boolean debugEventSent = false;
        

        for (int i = 0; i < arrivalTimes.size(); i++) {
            boolean isNext = false;
            boolean isShortened = false;
            boolean isOtherTrack = false;
            
            ArrivalTime stopTime = arrivalTimes.get(i);
            ArrivalTime previousStopTime = null;
            if (i > 0) {
                previousStopTime = arrivalTimes.get(i - 1);
                
                // Time should never decrease
                if (previousStopTime.getScheduledTime().compareTo(stopTime.getScheduledTime()) > 0) {           
                    // Very mysterious event, report to analytics (just once), so we can see where it happens
                    Log.e("StopTimesFragment", String.format("decreasing time %s -> %s", previousStopTime.getScheduledTime().getTime(), stopTime.getScheduledTime().getTime()));
                    if (!debugEventSent) {                       
                        EasyTracker.getTracker().trackEvent("debug", 
                            String.format("StopTimesFragment(%s,%s)", stopTime.getTrackId(), stopTime.getStopId()),
                            String.format("decreasing time %s -> %s", previousStopTime.getScheduledTime().getTime(), stopTime.getScheduledTime().getTime()),
                            0L
                        );
                        debugEventSent = true;
                    }
                }
            }
            
            int hours = stopTime.getScheduledTime().get(Calendar.HOUR_OF_DAY);
            String minutes = String.valueOf(stopTime.getScheduledTime().get(Calendar.MINUTE));
            if (minutes.length() == 1) {
                minutes = "0" + minutes;
            }
                    
            TextView minutesView = createMinutesView(minutes, stopTime.getRunId(), HourMinuteFormat.format(stopTime.getScheduledTime()));            

            if (!foundNextTime
                    && ((Integer.valueOf(hours) == currentHour && Integer.valueOf(minutes) >= currentMinute) || Integer
                            .valueOf(hours) > currentHour)) {                
                foundNextTime = true;
                isNext = true;
            }

            if (TrackType.SHORTENED.equals(stopTime.getTrackType())) {
                isShortened = true;
            }            
            if (!trackId.equals(stopTime.getTrackId())) {
                isOtherTrack = true;
            }
                        
            
            if (isShortened) {
                minutesView.setTextColor(getResources().getColor(R.color.times_shortened_color));                    
            } else if (isOtherTrack) {
                minutesView.setTextColor(getResources().getColor(R.color.times_othertrack_color));
            }   
            
            if (isNext) {
                minutesView.setBackgroundResource(R.drawable.times_next_selector);
                minutesView.setTypeface(null, Typeface.BOLD);
            }
            if (stopTime.getIsAccessible()) {
                minutesView.setBackgroundResource(R.drawable.times_isaccessible_selector);
            }
            

            if (previousStopTime == null
                    || hours != previousStopTime.getScheduledTime().get(Calendar.HOUR_OF_DAY)) {
                if (row != null) {
                    stopTimesTable.addView(row);
                }
                
                if (previousStopTime != null) {
                    for (int hr = previousStopTime.getScheduledTime().get(Calendar.HOUR_OF_DAY) + 1; hr < hours; hr++) {
                        // If hours are skipped, add empty rows
                        row = createTableRow();                
                        row.addView(createHoursView(String.valueOf(hr)));
                        stopTimesTable.addView(row);
                    }
                }
                
                row = createTableRow();                
                row.addView(createHoursView(String.valueOf(hours)));
            }
            row.addView(minutesView);
        }
        if (row != null) {
            stopTimesTable.addView(row);
        }
        else {
            view.findViewById(R.id.no_arrival_times).setVisibility(View.VISIBLE);
        }
    }
        
    private TableRow createTableRow() {
        TableRow row = new TableRow(getActivity());
        row.setBackgroundResource(R.color.primary);
        TableLayout.LayoutParams lp = new TableLayout.LayoutParams();
        lp.setMargins(0, 0, 0, 1);
        row.setLayoutParams(lp);
        return row;
    }
    
    private TextView createHoursView(String hours) {
        TextView hoursView = new TextView(getActivity());
        hoursView.setPadding(6, 0, 6, 0);
        hoursView.setText(hours);
        hoursView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        hoursView.setBackgroundResource(R.color.light_gray_background);
        hoursView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.textStopTimes)); 
        return hoursView;
    }
    
    private TextView createMinutesView(String minutes, String runId, String scheduledTime) {
        TextView minutesView = new TextView(getActivity());
        minutesView.setPadding(6, 0, 6, 0);
        minutesView.setText(minutes);            
        minutesView.setOnClickListener(new MinutesViewOnClickListener(runId, scheduledTime));
        minutesView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.textStopTimes));        
        minutesView.setBackgroundResource(R.drawable.color_selector);
        return minutesView;
    }
    
    
    
    
    private class MinutesViewOnClickListener implements View.OnClickListener
    {
      private String runId;
      private String scheduledTime;
      
      public MinutesViewOnClickListener(String runId, String scheduledTime) {
           this.runId = runId;
           this.scheduledTime = scheduledTime;
      }

      @Override
      public void onClick(View v)
      {
          sendItemData(runId, scheduledTime);
      }
   };

}
